package com.im.redis;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.im.entity.MessageEntity;
import com.im.util.RedisUtil;
import com.im.util.SessionUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

@Slf4j
public class SubscribeListener implements MessageListener {

    /**
     * 订阅者的消息接收方法
     *
     * @param message 参数
     * @param pattern 通道名称
     */
    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //接收发布的消息
        String  taskId = new String(message.getBody()).replace("\\","");
        taskId = taskId.substring(1,taskId.length()-1);
        //频道名称  须要和发布的名称一致，不然不会生效
        String pattrenStr = new String(pattern);
        //TODO 进行本身业务逻辑操做
        System.out.println("taskId:" + taskId + "   pattrent:" + pattrenStr);
        MessageEntity map = JSONUtil.toBean(taskId, MessageEntity.class);
        WebSocketSession webSocketSession = SessionUtil.get(map.getToId());
        if(null != webSocketSession){
            System.out.println("发送消息");
            webSocketSession.sendMessage(new TextMessage(map.getContent()));
        }
    }
}
